package com.work_attendance.attend.service;

import com.work_attendance.attend.dao.AttendMapper;
import com.work_attendance.attend.entity.Attend;

import com.work_attendance.common.utils.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("attendServiceImpl")
public class AttendServiceImpl implements AttendService{
    private static final int NOON_MINUTE = 00;
    private static final int NOON_HOUR = 12;
    private Log log= LogFactory.getLog(AttendServiceImpl.class);
    @Autowired
    private AttendMapper attendMapper;
    @Override
    public void signAttend(Attend attend) throws Exception {
        //打卡业务：
            //中午十二点之前打卡算早晨打卡，如果谁9.30以后打卡直接异常，算迟到
            //十二点以后打卡算下午打卡
            //下午打卡 检查与上午打卡的时间差,这里要使用定时器，不足八小时都算异常，并且缺席多长时间都存到数据库中
            //下午打卡18点之前算异常
            //打多次卡早上取最早的，下午取最晚的
        try {
            Date today=new Date();
            attend.setAttendDate(today);
            attend.setAttendWeek((byte)DateUtils.getTodayWeek());
            //查询当天此人的打卡记录
            Attend todayRecord=attendMapper.selectTodaySignRecord(attend.getUserId());
            Date noon= DateUtils.getDate(NOON_HOUR,NOON_MINUTE);
            if(todayRecord==null){
                //当天打卡记录还不存在
                if(today.compareTo(noon)<=0){
                    //打卡时间早于十二点
                    attend.setAttendMorning(today);
                }else {
                    attend.setAttendEvening(today);
                }
                attendMapper.insertSelective(attend);
            }else{
                //如果数据存在再次判断打卡时间
                //如果是早上打卡直接结束方法
                if(today.compareTo(noon)<=0){
                    //打卡时间早于十二点
                    return;
                }else {
                    //下午打卡则更新数据库的下午打卡时间
                    todayRecord.setAttendEvening(today);
                    attendMapper.updateByPrimaryKeySelective(todayRecord);
                }
            }



        }catch (Exception e){
            log.error("用户签到异常",e);//打卡的时候出现异常，就把异常记录在日志中
            throw e;//这里处理完日志必须要抛出这个异常，因为事务只有在抛出异常后才能回滚，处理了异常会导致事务不回滚
        }
    }
}
